package LC;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode.com/problems/binary-tree-inorder-traversal/description/
 * Given a binary tree, return the inorder traversal of its nodes' values.
 * For example:
 * Given binary tree [1,null,2,3],
 * return [1,3,2].
 */
public class LC_094_BinaryTreeInorderTraversal_BinaryTree_InOrderRecur {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);
        List<Integer> res = Solution.inorderTraversal(root);
        System.out.println(res);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static List<Integer> list = new ArrayList<>();

        static List<Integer> inorderTraversal(TreeNode root) {
            inOrder(root);
            return list;
        }

        private static void inOrder(TreeNode node) {
            if (node == null) return;
            if (node.left != null) inOrder(node.left);
            list.add(node.val);
            if (node.right != null) inOrder(node.right);
        }
    }

    static class Solution_2 {
        static List<Integer> list = new ArrayList<>();

        static List<Integer> inorderTraversal(TreeNode root) {
            if (root == null) return list;
            Stack<TreeNode> stack = new Stack<>();
            TreeNode tempNode = root;
            stack.push(tempNode);
            while (!stack.isEmpty()) {
                while ((tempNode = stack.peek()) != null) {
                    tempNode = tempNode.left;
                    stack.push(tempNode);
                }
                stack.pop();
                if (!stack.isEmpty()) {
                    tempNode = stack.pop();
                    list.add(tempNode.val);
                    stack.push(tempNode.right);
                }
            }
            return list;
        }
    }
}
